<?php
/**
 * 后台心愿管理
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/5/28 14:36
 * @copyright PanxSoft Inc.
 */

namespace App\Http\Controllers\Admin\V1;


use App\Http\Controllers\ApiController;
use App\Models\WishList;
use Illuminate\Http\Request;

class WishListController extends ApiController
{
    const ROUTES = [
        'index'        => 'admin.v1.wish-list.index',
        'patchRealize' => 'admin.v1.wish-list.patchRealize',
    ];

    /**
     * 心愿列表
     *
     * @param Request $request
     *
     * @return array|\Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $wish_lists = (new WishList)
            ->with('user')
            ->filterWhen('is_realized', $request->is_realized)
            ->oldest()
            ->paginate($request->per_page ?: 15);

        return $this->response(compact('wish_lists'));
    }

    /**
     * 完成心愿
     *
     * @param Request $request
     *
     * @param string $key
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function patchRealize(Request $request, $key)
    {
        /** @var WishList $wish_list */
        $wish_list = (new WishList)
            ->where('is_realized', WishList::NOT_REALIZED)
            ->find($key);
            $this->checkItemExist($wish_list);

        $realized = $wish_list->realize();

        return $this->response(compact('realized'));
    }
}